import KoaWebSocketServer from '../modules/KoaWebSocketServer';

const DEFAULTS = {
    heartbeat: false,
    heartbeatInterval: 5000,
};

function middleware(_app, router, opts) {
    const options = Object.assign({}, DEFAULTS, opts);

    // init websocket server
    const app = _app;
    const koaListen = app.listen;
    const log = app.log.getLogger('[wsm]');

    options.onOpen = app.clientPool.add.bind(app.clientPool);
    options.onClose = app.clientPool.del.bind(app.clientPool);
    options.onError = app.clientPool.del.bind(app.clientPool);

    app.ws = new KoaWebSocketServer(app, router, options);

    // override app.listen
    app.listen = (...args) => {
        app.server = koaListen.apply(app, args);
        app.ws.listen(app.server, () => log.info('attached'));
        app.address = () => app.server.address();
        return app;
    };

    return function* dispatch(next) {
        yield next;
    };
}


export default middleware;
